
package com.ibuu.demos.controller;

import com.ibuu.dto.LoginRequestDTO;
import com.ibuu.demos.pojo.User;
import com.ibuu.demos.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private LoginService service;


    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody LoginRequestDTO loginRequest, HttpServletRequest request) {
        boolean login = service.login(loginRequest.getUsername(), loginRequest.getPassword());
        if (login) {
            request.getSession().setAttribute("username", loginRequest.getUsername());
            return ResponseEntity.ok("Login successful");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }

    @GetMapping("/select")
    public User select(HttpServletRequest request) {
        String username = (String) request.getSession().getAttribute("username");
        System.out.println(username);
        User user = service.selectUser(username);
        return user;
    }

    @PostMapping("/update")
  public boolean update(@RequestBody User user) {

        return service.updateUser(user);
    }


    //注册用户
    @PostMapping("/register")
    public boolean register(@RequestBody User user) {

        return service.register(user);
    }
    //登出用户
    @GetMapping("/logout")
    public void logout(HttpServletRequest request){
        request.getSession().removeAttribute("username");
    }
}